package com.wm;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @ClassName: ThreadTest
 * @Description: 线程的创建与运行
 * @Author: WM
 * @Date: 2021-12-30 16:48
 **/
public class ThreadTest {
    /**
     * 一共三种方式
     * 1.继承Thread类并重写run方法
     * 2.实现Runnable接口的run方法
     * 3.使用FutureTask
     */
    // 继承Thread类并重写run方法
    public static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("I am a child Thread.");
        }

        public static void main(String[] args) {
            // 创建线程
            MyThread myThread = new MyThread();
            // 启动线程 就绪状态->运行状态（获取CPU资源后）->终止状态（任务执行完毕）
            myThread.start();
        }
    }

    // 实现Runnable接口的run方法
    public static class RunableTask implements Runnable {
        @Override
        public void run() {
            System.out.println("I am a child Thread.");
        }

        public static void main(String[] args) {
            RunableTask runableTask = new RunableTask();
            new Thread(runableTask).start();
            new Thread(runableTask).start();

        }
    }

    // 含有返回值的任务类
    public static class CallerTask implements Callable<String> {

        @Override
        public String call() throws Exception {
            return "hello";
        }

        public static void main(String[] args) {
            // 创建异步线程
            FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
            // 启动线程
            new Thread(futureTask).start();
            try {
                // 等待任务执行完毕，并返回结果
                String result = futureTask.get();
                System.out.println(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
